import random
from locust import HttpUser, tag, task, between, SequentialTaskSet


class MyTask(SequentialTaskSet):
    # 初始化
    def on_start(self):
        pass

    @task
    @tag("reg")
    def regUser(self):
        url = '/user/'
        headers = {'Content-Type': 'application/json'}
        username = "king_" + str(random.randint(0, 10000))
        pwd = '123456'
        phone = str(15800000000 + random.randint(1, 10000))
        age = random.randint(10, 120)
        data = {
            "userName": username,
            "password": pwd,
            "phone": phone,
            "age": age
        }
        with self.client.post(url, json=data, headers=headers, catch_response=True, name="注册") as res:
            print(res.json())
            if res.status_code != 200 and res.json()['code'] == 1:
                res.failure("注册失败")

    @task
    @tag("getUser")
    def getUser(self):
        url = '/user/{}/'.format(random.randint(5, 10000))
        with self.client.get(url, catch_response=True, name="查询用户") as res:
            print(res.json())
            if res.status_code != 200 and res.json()['code'] == 1:
                res.failure("查询失败！")

    # 清理数据
    def on_stop(self):
        pass


class UserRun(HttpUser):
    tasks = [MyTask]
    # wait_time = between(0.2, 2)
    min_wait = 10
    max_wait = 100

